<template>
  <div>
    <div>
      <div style="width: 100%;display:flex;justify-content: space-between">
        <div>
          <a-button type="primary" style="margin-top: 20px" @click="editModal(0)">新建</a-button>
        </div>
        <div>
          <a-select style="width: 100px;" v-model="queryParam.nid" placeholder="请选择" default-value="">
            <a-select-option value="">全部</a-select-option>
            <a-select-option value="atc-banner">轮播图</a-select-option>
            <a-select-option value="atc-notice">通告</a-select-option>
            <a-select-option value="atc-faq">常见问题</a-select-option>
          </a-select>
          <a-button type="primary" style="margin-top: 20px" @click="getArticleList">查询</a-button>
        </div>
      </div>
    </div>
    <div style="margin-top: 20px">
      <a-table :pagination="false" :columns="columns" :data-source="articleList" rowKey="id">
      <span slot="state" slot-scope="state">
      <a-tag :color="state === -1 ? 'red' : 'cyan'">
        {{ state === -1 ? '禁用' : '使用中' }}
      </a-tag>
    </span>
        <span slot="action" slot-scope="text, record">
          <a-button type="primary" icon="edit" size="small" @click="editModal(record)"></a-button>
        </span>
      </a-table>
      <div style="margin-top: 20px;text-align: center">
        <a-pagination v-model="current" :page-size="pageSize" :total="total" @change="changePage"/>
      </div>
    </div>
    <div>
      <a-modal width="1000px" v-model="visible" title="编辑" @ok="handleOk" @cancel="handleCancel">
        <a-form :form="form">

          <a-form-item>
            <a-input v-if="articleMdl.id > 0" v-decorator="['id', { initialValue: articleMdl.id } ]" hidden/>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="标题">
            <a-input
              v-decorator="['title',{ initialValue: articleMdl.title },{rules: [{required: true,message: '请填写标题'}]}]"/>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="简介">
            <a-input
              placeholder="简短的介绍"
              v-decorator="['introduction',{ initialValue: articleMdl.introduction },{rules: [{required: true,message: '请填写简介'}]}]"/>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="外链接">
            <a-input
              v-decorator="['url',{ initialValue: articleMdl.url }]"/>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="图片">
            <a-input
              hidden
              v-decorator="['picPath']"/>
            <img v-if="articleMdl.picPath" width="275px" height="175px" :src="articleMdl.picPath" alt="">
            <a v-if="articleMdl.picPath" @click="handlePicPathRemove">删除</a>
            <a-upload
              :beforeUpload="beforeUpload"
              @change="handleChange"
              v-if="!articleMdl.picPath"
            >
              <a-button> <a-icon :type="uploading ? 'loading' : 'upload'" /> {{ uploading ? '上传中...':'选择图片'}} </a-button>
            </a-upload>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="内容"
            hasFeedback
          >
            <a-textarea
              :rows="10"
              placeholder="..."
              id="content"
              v-decorator="['content', {initialValue: articleMdl.content}]"
            />
          </a-form-item>
          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="类型"
          >
            <a-select v-decorator="['nid',{initialValue: articleMdl.nid}]">
              <a-select-option value="atc-faq">常见问题</a-select-option>
              <a-select-option value="atc-notice">通知</a-select-option>
              <a-select-option value="atc-banner">轮播图</a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item
            :labelCol="labelCol"
            :wrapperCol="wrapperCol"
            label="是否启用"
          >
            <a-radio-group v-decorator="['state', { initialValue: articleMdl.state}]">
              <a-radio :value="1">
                启用
              </a-radio>
              <a-radio :value="-1">
                禁用
              </a-radio>
            </a-radio-group>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>

  </div>
</template>

<script>
  import { getArticleList, saveOrUpdateArticle } from "../../api/content";
  import {compressByImg} from "../../utils/imgUtil";
  import {uploadImgByBase64} from "../../api/common";
  const columns = [
    {
      title: '编号',
      dataIndex: 'id',
      key: 'id',
    },
    {
      title: '标题',
      dataIndex: 'title',
      key: 'title',
    },
    {
      title: '简介',
      key: 'introduction',
      dataIndex: 'introduction'
    },
    {
      title: '状态',
      key: 'state',
      dataIndex: 'state',
      scopedSlots: {customRender: 'state'},
    },
    {
      title: '操作',
      key: 'action',
      scopedSlots: {customRender: 'action'},
    },
  ];
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
  export default {
    name: "ArticleList",
    data() {
      return {
        visible: false,
        articleList: [],
        form: '',
        queryParam: {
          nid: '',
          state: 0
        },
        current: 1,
        pageSize: 15,
        total: 0,
        columns,
        articleMdl: {
          nid: "atc-faq",
          title: '',
          introduction : '',
          url: '',
          content: '',
          picPath: ''
        },
        uploading: false,
        labelCol: {
          xs: {span: 24},
          sm: {span: 6}
        },
        wrapperCol: {
          xs: {span: 24},
          sm: {span: 12}
        },
      }
    },
    mounted() {
      this.getArticleList()
    },
    methods: {
      changePage() {
        this.getArticleList()
      },
      async getArticleList() {
        this.articleList = []
        this.queryParam["pageNo"] = this.current
        this.queryParam["pageSize"] = this.pageSize
        const result = await getArticleList(this.queryParam)
        let pageInfo = result.data.page
        this.total = pageInfo.totalPage
        this.articleList = pageInfo.list
      },
      editModal(record) {
        this.articleMdl = ''
        this.articleMdl = Object.assign({}, record === 0 ? this.articleMdl : record)
        this.form = this.$form.createForm(this)
        this.visible = true
      },
      beforeUpload() {
        return false
      },
      async handleChange(info) {
        this.uploading = true
        const base64 = await compressByImg(info.file);
        const result =  await uploadImgByBase64({
          base64: base64,
          fileName: info.file.uid,
          parentPath: 'article_img'
        })
        if (result.code > 0) {
          this.articleMdl.picPath = result.data.remoteUrl
          this.form.setFieldsValue({ picPath: result.data.remoteUrl });
        } else {
          this.$me("上传失败")
        }
        this.uploading = false
      },
      handlePicPathRemove() {
        this.form.setFieldsValue({ picPath: '' });
        this.articleMdl.picPath= ''
      },
      close () {
        this.$emit('close')
        this.visible = false
      },
      handleOk() {
        this.form.validateFields(async (err, values) => {
          if(!err) {
            const result = await saveOrUpdateArticle(values);
            if (result.code > 0) {
              this.close()
              this.getArticleList()
              this.form = this.$form.createForm(this)
              this.visible = false
            } else {
              this.$me(result.message)
            }
          }
        })

      },
      handleCancel() {
        this.close()

      },
    }
  }
</script>

<style scoped>
</style>
